package com.sky.happygos.base;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.WindowManager;

import com.google.gson.Gson;
import com.sky.happygos.model.RestMessage;
import com.sky.happygos.ui.activity.LoginA_;

import java.io.IOException;
import java.util.Date;

import retrofit2.Response;

import static com.sky.happygos.ui.activity.LoginA.EXECT_CHECK_TOKEN;


/**
 * Created by qqqqqqq on 2017/4/17.
 */

public class ErrorHandler {
    public static Gson gson = new Gson();
    public static Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            open = false;
        }
    };
    public static boolean open = false;


    public static RestMessage handler(Response response){
        okhttp3.ResponseBody g = response.errorBody();
        String error = null;
        RestMessage errorMessage;
        try {
            error = g.string();
            errorMessage = gson.fromJson(error,RestMessage.class);
        } catch (Exception e) {
            e.printStackTrace();
            errorMessage =  new RestMessage(-2,"未知错误");
        }

        processError(errorMessage);
        return errorMessage;
    }

    public static void processError(RestMessage error){
        switch (error.code){
            case 6:{
                showDialog();
                break;
            }
        }
    }

    public static void showDialog() {

        if (!open) {
            Activity activity = YActivityManage.getInstance().getCurrentActivity();
            if (activity != null) {
                AlertDialog dialog = new AlertDialog.Builder(activity)
                        .setCancelable(false)
                        .setTitle("提示")
                        .setMessage("账户已过期，请重新登录")
                        .setNegativeButton("取消",new DialogInterface.OnClickListener(){

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                YActivityManage.getInstance().finishAll();
                                LoginA_.intent(MyApplication.getContext()).extra(EXECT_CHECK_TOKEN, "NO").start();
                            }
                        }).create();
                dialog.show();
            }
            open = true;
            handler.sendMessageDelayed(new Message(),3000);
        }
    }
}
